<template>
	<view class="flex flex-direction bg-white" style="width: 100vw; height: 100vh;">
		<cu-custom :isBack="true">
			<block slot="content">
				<text style="font-size: 32rpx;">订单确认页</text>
			</block>
		</cu-custom>
		<view class="flex-sub flex flex-direction justify-between align-center bg-white">
			<view class="flex flex-direction" style="width: 100%;padding: 0 32rpx;">
				<view style="margin-top: 28rpx;font-size: 40rpx;font-weight: bold;color: #1C1C1E;line-height: 44rpx;">
					{{order.contentTitle}}
				</view>
				<view style="margin-top: 20rpx;font-size: 32rpx;color: #999999;line-height: 40rpx;">
					<rich-text :nodes="order.description"></rich-text>
				</view>
				<view style="margin-top: 72rpx;font-size: 48rpx;font-weight: bold;color: #FF3B30;line-height: 64rpx;">
					¥{{order.totalFee}}
				</view>
				<view style="margin-top: 40rpx;">
					<checkbox-group @change="agree = !agree">
						<label class="flex align-center">
							<checkbox :class="agree?'checked':''" :checked="agree?true:false" style="transform:scale(0.9)"></checkbox>
							<text style="font-size: 34rpx;color: #666666;margin-left: 20rpx;">同意
								<text style="color: #007AFF;">《学问宝服务协议》</text>
							</text>
						</label>
					</checkbox-group>
				</view>
				<view style="margin-top: 54rpx;font-size: 32rpx;font-weight: bold;color: #1C1C1E;line-height: 44rpx;">
					支付方式
				</view>
				<view style="margin-top: 40rpx;">
					<radio-group style="width: 100%;" @change="selectedProvider = (selectedProvider+1)%providerList.length">
						<label v-for="(item, index) in providerList" :key="index" class="flex justify-between align-center margin-top">
							<view class="flex align-center">
								<image style="width: 60rpx;height: 60rpx;" :src='"../../static/pay/provider"+(index+1)+".png"'></image>
								<text style="margin-left: 20rpx;font-size: 40rpx;color: #1C1C1E;line-height: 44rpx;">
									{{providerListName[index]}}
								</text>
							</view>
							<radio class="radio" :class="selectedProvider==index?'checked':''" :checked="selectedProvider==index?true:false"></radio>
						</label>
					</radio-group>
				</view>
			</view>
			
			<!-- #ifndef H5 -->
			<view @click="uni.navigateBack({ delta: 1 });" v-if="status !== 1 && isPaying" class="flex justify-center align-center confirm-button opacity-button">
				放弃支付
			</view>
			<view @click="pay" v-if="status !== 1 && !isPaying" class="flex justify-center align-center confirm-button" :class="(!agree)?'opacity-button':''">
				确认支付
			</view>
			<!-- #endif -->
			
			<!-- #ifdef H5 -->
			<view v-if="order.totalFee>0.0" class="flex flex-direction justify-center align-center">
				<view @click="pay" v-if="!codeUrl && status !== 1" class="flex justify-center align-center confirm-button" :class="!agree?'opacity-button':''">
					获取支付二维码
				</view>
				<template v-if="codeUrl && status !== 1">
					<image style="width: 400rpx;height: 400rpx;" :src="'https://api.pwmqr.com/qrcode/create/?url=' + codeUrl" mode="widthFix"></image>
					<button type="primary" @click="orderQuery" class="flex justify-center align-center confirm-button">我已完成支付</button>
				</template>
			</view>
			<view v-if="status !== 1 && order.totalFee==0.0" @click="orderQuery" class="flex justify-center align-center confirm-button" :class="!agree?'opacity-button':''">
				下单
			</view>
			<!-- #endif -->
			
			<view @click="$Router.push($store.getters.pagePrevious)" v-if="status == 1" class="flex justify-center align-center confirm-button">
				已支付,去学习
			</view>
			
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				providerList: ['wxpay','alipay'],
				providerListName: ['微信支付', '支付宝'],
				selectedProvider: 0,
				agree: false,
				isPaying: false,
				status: 0,
				codeUrl: '',
				order: {},
				outTradeNo: this.$Route.query.outTradeNo?this.$Route.query.outTradeNo:'20210707222741469',
			}
		},
		methods: {
			// #ifdef H5
			pay() {
				let provider = this.providerList[this.selectedProvider];
				this.$http.get(`/eduorder/paylog/createNative/${provider}/${this.outTradeNo}`).then((res) => {
					let data = res.data;
					if(data.success) {
						// console.log(res)
						this.codeUrl = data.result.code_url;
						this.status = data.result.status;
					} else {
						this.$tip.alert(data.message)
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '获取支付二维码失败',
						showCancel: false
					})
				})
			},
			orderQuery() {
				uni.showLoading({
					title: '支付中',
					mask: true
				})
				this.$http.get(`/eduorder/paylog/queryPayStatus/${this.outTradeNo}`).then((res) => {
					uni.hideLoading()
					let data = res.data;
					this.$Router.push({
						name: "payResult",
						params: {
							data: data
						}
					})
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: '查询订单状态失败，请稍后再试',
						showCancel: false
					})
				})
			},
			// #endif
			
			// #ifndef H5
			pay() {
				let provider = this.providerList[this.selectedProvider];
				this.$http.get(`/eduorder/paylog/createALiPay/${this.outTradeNo}`).then((res) => {
					console.log(res);
					let data = res.data;	
					if(data.result.orderString) { //支付宝返回的是 orderString
						data.result.orderInfo = data.result.orderString;
					}
					console.log(data.result.orderInfo)
					if (data.result.orderInfo) {
						return new Promise((resolve, reject) => {
							if(this.develop) {	//判断开发环境
								//支付宝沙箱环境, 依赖原生插件 https://ext.dcloud.net.cn/plugin?id=5224
								const ljAliPay = uni.requireNativePlugin('lj-alipay');
								ljAliPay.pay({ // 发起支付
									auto_builder_order_info: false, //是否自动生成订单信息必填
									appId: '2021000118600112',  //支付宝APPID必填
									rsa2_private: "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHmcPuiWLPG+zpOqlgoZKXnOq+TXVrmjSCEULGwQdKuRlIdQY986JBT438mu63soGxiLC98zbpDGzot/xWamoEqUu4RvVJ21bF7jWI77yP77IbAb/F8k51lhKNggtpCAZwSUlcWjkqkv0QUqFY9c2+vNZ0J5FuQiI9z2HavbOPEoz8KTYWcA9vO5gRi0NwBcA1B84hFYgRB7oPnwjsfDSticVe1mcQpU9xwuA97+r3LnNWFCUhzWy/QteLJ4ijFd2DwSfqDnSou53etiDw1u359KtJTiIYKXRJUtkIn/g0xSRlEwjiuOnqIX9rgIkmVRV9c0l/5YBkBUTtHWSruoBTAgMBAAECggEATFessMJWh+Xf9tsY+xdcMdGdc7CmWANEZqoTH1UTpuUZL+r6raxaAE0q0jnkBjYQwIQFhZvFoWVmd4sGHRziPWeXAtOoS4Gak+rt5v+Z+Ktpab0NXAN0Ws03+sVpaSOkhFkuXTlKkAabRTJQNoaE5ErqrhCM1zeSkZwNKpq82e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//订单信息,auto_builder_order_info为false时必填
								}, function(res) { // 支付完成回调
									const result = res.result
									console.log(res);
									if (result.resultStatus == '5002555') { 
										uni.showToast({
											title:'支付sdk出错',
											icon:'none'
										})
								
									} else if (result.resultStatus == '9000') {
										uni.showToast({
											title: '支付成功',
											icon: 'none'
										})
										resolve(data.result.outTradeNo)
									} else {
										uni.showToast({
											title: ''+result.memo,
											icon: 'none'
										})
									}
								});
							} else {
								//支付宝真实环境 (沙箱不可用)
								uni.requestPayment({
									// #ifdef APP-PLUS
									provider: provider,
									// #endif
									// #ifdef MP-WEIXIN
									...data.result.orderInfo,
									// #endif
									// #ifdef APP-PLUS || MP-ALIPAY
									orderInfo: data.result.orderInfo,
									// #endif
									complete() {
										resolve(data.result.outTradeNo)
									}
								})
							}	
						})
					} else {
						console.log("error1")
						throw new Error(data.message)
					}
				}).then((outTradeNo) => {
					console.log("error2")
					this.isPaying = true;
					uni.showLoading({
						title: '支付中',
						mask: true
					})
					return this.$http.get(`/eduorder/paylog/queryAliPayStatus/${this.outTradeNo}`)
				}).then((res) => {
					console.log("error3")
					uni.hideLoading()
					let data = res.data;
					console.log(data)
					this.$Router.push({
						name: "payResult",
						params: {
							data: data
						}
					})
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: '支付失败，请稍后再试',
						showCancel: false
					})
				})
			}
			// #endif
		},
		onLoad() {			
			// console.log("outTradeNo", this.outTradeNo);
			uni.showLoading({
				title: '正在获取订单',
				mask: true
			})
			this.$http.post('/eduorder/order/getOrderInfo', {
				orderId: this.outTradeNo
			}).then((res) => {
				uni.hideLoading()
				let data = res.data;
				if(data.success) {
					this.order = data.result;
					console.log("order", this.order)
				}
			}).catch((err) => {
				uni.hideLoading()
				console.log(err)
			})
		},
	}
</script>

<style>
	.confirm-button {
		width: 660rpx;
		height: 100rpx;
		margin-bottom: 10rpx;
		background: #007AFF;
		border-radius: 8rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #FFFFFF;
		line-height: 44rpx;
	}
	.opacity-button{
		opacity: 0.5;
	}
</style>
